package bucket

import (
	"clouds.lgb24kcs.cn/controllers/bucket/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/history"
	"clouds.lgb24kcs.cn/utils/oss"
	"github.com/gin-gonic/gin"
)

type DelBucket struct {
}

var DelAPI DelBucket

func (d DelBucket) DelBucket(c *gin.Context, req request.DeleteBucketReq, userId int64) {
	api := oss.OSS{}
	bucket := models.Storage{}
	tx := global.APP.DB.Where("id=? and bucketname=? and userid=?", req.Id, req.BucketName, userId).First(&bucket)
	if tx.Error != nil || tx.RowsAffected == 0 {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.BucketDel, "删除失败")
	} else {
		client := api.NewClient(bucket.Accesskey, bucket.Secretkey, bucket.Zone)
		err := api.DeleteBucket(client, bucket.Bucketname)
		if err != nil {

			global.APP.Log.Error(err.Error())
			utils.Fail(c, errorx.BucketDel, err.Error())

		} else {
			db := global.APP.DB.Delete(&bucket)
			if db.Error != nil {
				global.APP.Log.Error(tx.Error.Error())
				utils.Fail(c, errorx.BucketDel, err.Error())
			} else {
				if err := history.HistoryCreate(userId, c.Request.Method, c.Request.URL.String(), c.Request.Host); err != nil {
					utils.Fail(c, errorx.ObjectSearch, err.Error())
				} else {
					utils.Success(c, 0, "删除成功")
				}
			}
		}
	}
}
